const App = getApp();
// 工具类
import Util from '../../../utils/util.js';
Page({
  /**
   * 页面的初始数据
   */
  onShareAppMessage() {
    return {
      title: 'picker-view',
      path: 'page/component/pages/picker-view/picker-view'
    }
  },
  data: {
    freshen :true,
    isLogin: false,
    teamId:0,
    detail:{},
    maoHao: '：',
    fileList: [],
    banner_id:0,
    fileList1: [],
    image_id:0,
    fileList2: [],
    categoryList:[],
    cateindex:0,
    cate_name:'',//分类选中回显
    cate_id:0,//选中的分类ID
    display:1, //1全员可见，2本队可见
    address:"",
    latitude:"", //纬度
    longitude:"",//经度
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    console.log('user_info',wx.getStorageSync('user_info'));
    let that = this;
    if(that.data.freshen){
      that.setData({
        isLogin: App.checkIsLogin(),
      });
      if (that.data.isLogin) {
        //获取服务队
        that.setData({
          teamId: App.checkTeam()
        });
        // 分类
        that.getCate(); 
        // 资讯详情
          that.getDetail();
      }
    }
  },
  // 分类
  getCate(){
    let that = this;
    App._get('company', {}, result => {
      that.setData({
        categoryList: result.data.categoryList
      }); 
    });
  },
  /**
   * 详情
   */
  getDetail() {
    let _this = this;
    App._get('company/companyInfo', {}, result => {
      if(result.data.detail){
        // banner将图片信息添加到fileList数字中
        const fileList = [];
        fileList.push({
          file_id:result.data.detail.banner.file_id,
          url:result.data.detail.banner.file_url+"/"+result.data.detail.banner.file_name
        });
        let banner_id = result.data.detail.banner.file_id
        // 封面图片信息添加到fileList1数字中
        const fileList1 = [];
        fileList1.push({
          file_id:result.data.detail.image.file_id,
          url:result.data.detail.image.file_url+"/"+result.data.detail.image.file_name
        });
        let image_id = result.data.detail.image.file_id
        _this.setData({
          detail: result.data.detail,
          cate_id:result.data.detail.category.category_id,
          cate_name:result.data.detail.category.name,
          display:result.data.detail.display,
          address: result.data.detail.address,
          longitude: result.data.detail.longitude,
          latitude: result.data.detail.latitude,
          fileList,
          fileList1,
          image_id,
          banner_id,
          fileList2:result.data.detail.goods
        })
      }
    });
  },

   // 删除照片
  deleteClick(event) {
    let type = event.currentTarget.dataset.id
    var imgData = (type==1)?this.data.fileList1:this.data.fileList;
    // 通过splice方法删除图片
    imgData.splice(event.detail.index, 1);
    // 更新图片数组
    if(type == 1){
      this.setData({
          fileList1: imgData,
          image_id:0
      })
    }else{
      this.setData({
        fileList: imgData,
        banner_id:0
    })
    }
  },
  // 图片上传
  afterRead(event) {
    let type = event.currentTarget.dataset.id
    let that = this;//防止this指向问题
    // loading加载
    wx.showLoading({title: '上传中...'});
    //获取图片详细信息
    const {file} = event.detail;
    //调用上传图片方法
    that.uploadCompressImg(file).then(res=>{
      App.uploadFile(res,{},function(result){
        const fileList = [];
            // // 将图片信息添加到fileList数字中
            fileList.push({
                url: result.data.file_path,
                file_id:result.data.file_id,
            });
            // 更新存放图片的数组
            console.log("type",type)
            console.log(fileList)
            if(type ==1){
              that.setData({
                image_id:result.data.file_id,
                fileList1:fileList
              });
            }else{
              that.setData({
                banner_id:result.data.file_id,
                fileList:fileList
              });
            }
            wx.hideLoading();//停止loading
      })
    })

  },
  
  //提交
  formSubmit(e) {
    var formData=e.detail.value;//获取表单数据
    if(formData.company_name == ""){
      App.showError("公司名称不能空!");
      return;
    }
    if(formData.phone == ""){
      App.showError("联系电话不能空!");
      return;
    }
    // if(!this.data.fileList1.length){
    //   App.showError("封面图片不能空!");
    //   return;
    // }
    // if(!this.data.fileList.length){
    //   App.showError("banner图片不能空!");
    //   return;
    // }
    if(formData.address == ""){
      App.showError("公司地址不能空!");
      return;
    }
    // if(formData.company_content == ""){
    //   App.showError("内容不能空!");
    //   return;
    // }
    
    let obj = {
      company_name:formData.company_name, //标题
      phone:formData.phone, //电话
      display:this.data.display,
      address:formData.address, //联系地址（详细）
      latitude:formData.latitude, //纬度
      longitude:formData.longitude, //经度
      company_content:formData.company_content, //内容
      image_id:this.data.image_id,//fileList1[0].file_id, //封面图片ID
      banner_id:this.data.banner_id,//this.data.fileList[0].file_id, //banner图片ID
      category_id:this.data.cate_id==0?this.data.categoryList[this.data.cateindex].category_id:this.data.cate_id//分类id
    };
    console.log(obj)
    App._post_form('company/release', obj, result => {
      //成功提示
      App.showSuccess(result.msg,function(){
        if(JSON.stringify(result.data)!=="{}"){
          App.navigationTo(result.data.url)
        }
      });
    });
  },

  //电话可见范围
  radioChange(e) {
    this.setData({
      display:e.detail.value
    })
  },

  //选择分类
  bindPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      cateindex: e.detail.value,
      cate_id:this.data.categoryList[e.detail.value].category_id,
      cate_name:this.data.categoryList[e.detail.value].name,
    })
  },
  //地图选择地址
  chooseLocation(){
    wx.chooseLocation({
      success: (res) => {
        console.log(res)
        if(res.address!='' && res.name!=''){
          this.setData({
            address:res.address,
            latitude:res.latitude,
            longitude:res.longitude,
            freshen:false
          })
        }
        return false
      },
    })
  },
  // 删除照片
  deleteClick2(event) {
    var imgData = this.data.fileList2;
    // 通过splice方法删除图片
    imgData.splice(event.detail.index, 1);
    console.log(event.detail)
    let that = this;
    App._get('upload/delImage', {
      fileIds:event.detail.file.id,
      table:"company_image"
    }, result => {

      // 更新图片数组
      this.setData({
        fileList2: imgData
      }) 

    });

  },
  // 图片上传
  afterRead2(event) {
    let that = this;//防止this指向问题
    //获取图片详细信息
    const {file} = event.detail;
    //调用上传图片方法
    that.uploadCompressImg(file).then(res=>{
      App.uploadFile(res,{user_id:wx.getStorageSync('user_id')},function(result){
        // 上传完成需要更新 fileList2
        const fileList2 = that.data.fileList2;
        // 将图片信息添加到fileList2数字中
        fileList2.push({
            ...file,
            url: result.data.file_path,
            image_id:result.data.file_id,
        });
        // 更新存放图片的数组
        that.setData({
            fileList2
        });
        //停止loading 
        wx.hideLoading();
      })
    })

   
  },
  //大小超了
  oversize(event){
    App.showError("图片大小不能超过10M");
    return;
  },
  //图片压缩
  uploadCompressImg(file) {
    let that = this
    return new Promise(function(resolve, reject){
      let file_url = file.tempFilePath
      console.log(file);
      if(file.size < 500*1024){
        console.log("size",file.size)
        console.log("file_url",file_url)
        resolve(file_url);
      }else{
         // 获得原始图片大小
          wx.getImageInfo({
            src: file_url,
            success(res) {
              console.log(res);
            
              let originHeight = res.height;
              let originWidth = res.width;
              // 压缩比例
              // 最大尺寸限制
              let maxWidth = 1024,
                maxHeight = 1024;
              // 目标尺寸
              let targetWidth = originWidth,
                targetHeight = originHeight;
              // 等比例压缩，如果宽度大于高度，则宽度优先，否则高度优先
              if (originWidth > maxWidth || originHeight > maxHeight) {
                if (originWidth / originHeight > maxWidth / maxHeight) {
                  // 要求宽度*(原生图片比例)=新图片尺寸
                  targetWidth = maxWidth;
                  targetHeight = Math.round(maxWidth * (originHeight / originWidth));
                } else {
                  targetHeight = maxHeight;
                  targetWidth = Math.round(maxHeight * (originWidth / originHeight));
                }
              }

              // 更新 canvas 大小
              that.setData({
                "cw": targetWidth,
                "ch": targetHeight
              });
              // 尝试压缩文件，创建 canvas
              let ctx = wx.createCanvasContext('canvas');
              ctx.clearRect(0, 0, targetWidth, targetHeight);
              //通过得到图片旋转的角度来调整显示方向以正确显示图片，主要解决 ios 系统上的图片会有旋转的问题
              let orientation = res.orientation;
              if (orientation == 'right') { //exif的6
                that.setData({
                  "cw": targetHeight,
                  "ch": targetWidth
                });
                ctx.rotate(90 * Math.PI / 180);
                ctx.drawImage(file_url, 0, 0, targetWidth, targetHeight, 0, -targetHeight, that.data.ch, that.data.cw);
              } else {
                ctx.drawImage(file_url, 0, 0, targetWidth, targetHeight);
              }

              ctx.draw(false, function () {
                // 获得新图片输出
                wx.canvasToTempFilePath({
                  x: 0,
                  y: 0,
                  canvasId: 'canvas',
                  destWidth: targetWidth,
                  destHeight: targetHeight,
                  quality: 0.9,
                  fileType: "jpg",
                  success: (res) => {
                    console.log(res)
                    resolve(res.tempFilePath);
                  },
                  fail: (err) => {
                    console.error(err)
                  }
                }, this)
              })
            }
          })
      }
    })
  },

})